package com.dev.ac.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dev.ac.common.Const;
import com.dev.ac.common.StudentTemplate;
import com.dev.ac.entity.AUser;
import com.dev.ac.exception.WebException;
import com.dev.ac.service.AUserService;
import com.dev.ac.mapper.AUserMapper;
import com.dev.ac.util.JwtUtil;
import com.dev.ac.util.RedisUtil;
import com.dev.ac.vo.LoginVo;
import com.dev.ac.vo.UserNewPassword;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author object
 * @description 针对表【a_user】的数据库操作Service实现
 * @createDate 2024-04-14 16:13:24
 */
@Service
public class AUserServiceImpl extends ServiceImpl<AUserMapper, AUser>
		implements AUserService {

	@Autowired
	RedisUtil redisUtil;
	@Autowired
	JwtUtil jwtUtil;
	@Autowired
	HttpSession httpSession;

	@Override
	public Object login(LoginVo loginVo) {
		AUser username = this.getOne(new QueryWrapper<AUser>()
				.eq("username", loginVo.getUsername())
		);
		Assert.notNull(username, "当前用户不存在");
		Assert.isTrue(username.getIsDelete() == 0, "用户已禁用，请联系管理员");

		if (!username.getPassword().equals(SecureUtil.md5(loginVo.getPassword()))) {
			// 自定义的异常类
			throw new WebException("用户名或密码错误");
		}
		if (!redisUtil.get(loginVo.getUuid()).equals(loginVo.getCode())) {
			//
			throw new WebException("验证码错误");
		}
		String token = jwtUtil.generateToken(username.getId(), Const.GRADE_USER);
		return MapUtil.builder()
				.put("userinfo", username)
				.put("token", token)
				.build();
	}


	@Override
	public Integer getCurrentId() {
		Integer username = (Integer) httpSession.getAttribute("username");
		System.out.println(username);
		return username;
	}

	@Override
	public Object selectList() {
		List<AUser> list = this.list();
		System.out.println("学生列表--" + list);
		return list;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void batchInsertUser(List<StudentTemplate> students) {
		for (StudentTemplate student : students) {
			AUser aUser = new AUser();
			aUser.setUsername(String.valueOf(student.getUsername()));
			aUser.setPassword(SecureUtil.md5("123456"));
			aUser.setNickname(student.getNickname());
			aUser.setAddress(student.getAddress());
			if (student.getEmail() != null) {
				aUser.setEmail(student.getEmail());
			}
			aUser.setIsDelete(0);
			aUser.setDepartment(student.getDepartment());
			aUser.setSchool(student.getSchool());
			aUser.setCreateTime(LocalDateTime.now());
			long count = this.count(new QueryWrapper<AUser>()
					.eq("username", aUser.getUsername())
			);
			if (count <= 0) {
				this.save(aUser);
			} else {
				this.update(aUser, new UpdateWrapper<AUser>()
						.eq("username", aUser.getUsername())
				);
			}

		}
	}

	/***密码修改**/
	@Transactional(rollbackFor = Exception.class)
	@Override
	public Object NewPasswordService(UserNewPassword newPassword, HttpServletRequest httpServletRequest) {
		String token = httpServletRequest.getHeader("token");
		Claims claimByToken = jwtUtil.getClaimByToken(token, Const.GRADE_USER);
		Integer subject = Integer.valueOf(claimByToken.getSubject());
		if (!redisUtil.get(newPassword.getUuid()).equals(newPassword.getVerificationcode()))
		{
			throw new WebException("验证码错误");
		}
		boolean update = this.update(new UpdateWrapper<AUser>()
					.eq("id", subject)
					.set("password", SecureUtil.md5(newPassword.getNewpassword())));
		return update;
	}

	/***学生信息更新**/
	@Override
	public Object UpdateInformationService(AUser aUser, HttpServletRequest httpServletRequest) {
		String token = httpServletRequest.getHeader("token");
		Claims claimByToken = jwtUtil.getClaimByToken(token, Const.GRADE_USER);
		Integer subject = Integer.valueOf(claimByToken.getSubject());
		boolean updated = this.update(new UpdateWrapper<AUser>()
				.eq("id", subject)
				.set("nickname", aUser.getNickname())
				.set("email", aUser.getEmail())
				.set("address", aUser.getAddress())
				.set("department", aUser.getDepartment()));
		return updated;
	}
}




